package com.android.webframework;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Environment;

public class PictureService extends WebService {
	RequestObject requestOb;
	File picLoc;
	
	/**
	 * Argument PictureFramework constructor
	 * @param requestOb
	 */
	public PictureService(RequestObject requestOb) {
		servicesLog.setLogTag("PicSvc");
		this.requestOb = requestOb;
	}
	
	/**
	 * Request a service
	 * @return a response object
	 * @see ResponseObject
	 */
	public ResponseObject request() throws RequestException {
		try {
			picLoc = new File(Environment.getExternalStorageDirectory(), "picfile.png");
			URL picURL = new URL((String)requestOb.getParameter("url"));
			HttpURLConnection con = (HttpURLConnection) picURL.openConnection();
			con.setRequestMethod("GET");
			con.setDoOutput(true);
			con.connect();
			
			servicesLog.appendToLog("File connecion established");
			
			FileOutputStream f = new FileOutputStream(picLoc);
			
			servicesLog.appendToLog("Local file open");
			
			InputStream in = con.getInputStream();
			
			byte[] buffer = new byte[1024];
	        int len1 = 0;

	        while ((len1 = in.read(buffer)) > 0) {
	            f.write(buffer, 0, len1);
	        }
	        f.close();
	        servicesLog.appendToLog("Successfully downloaded file");
		}
		catch (Exception e) {
			servicesLog.appendToLog("File download failed. Error:" + e.getClass() + e.getMessage());
		}
		return new ResponseObject(picLoc);
	}
}

